#!/usr/bin/python
# -*- coding: utf-8 -*-

__all__ = [
           u'FileWriter',
           u'LogWriter',
           u'StdTerminalWriter',
           u'NullWriter'
           ]

import sys

from _pylot.core.system import ENCODING
from _pylot.core.utils import (check_type, check_value)
from _pylot.interfaces.writer import WriterInterface

class NullWriter (WriterInterface):
  def __init__ (self):
    WriterInterface.__init__(self)
  def _write (self, text, style):
    return

class StdTerminalWriter (WriterInterface):

  def __init__ (self, stream=sys.stdout):
    super(WriterInterface, self).__init__()
    check_value(u'stream', stream, [sys.stdout, sys.stderr])
    self.stream = stream

  @classmethod
  def formatText (cls, text, style):
    if text is None :
      return ''

    if isinstance(text, unicode) :
      text = text.encode(ENCODING, u'replace')
    else :
      text = str(text)

    if style == u'title' :
      line = '-' * min(len(text), 80)
      text = '\n%s\n%s\n%s\n' % (line, text, line)
      text = '\033[1;34m%s\033[0;0m' % text
    elif style == u'warn':
      text = '\033[1;31m%s\033[0;0m' % text
    elif style == u'info':
      text = '\033[1;30m%s\033[0;0m' % text
    else :
      pass
    return text

  def _write (self, text, style):
    self.stream.write(self.formatText(text, style))
    self.stream.flush()

class FileWriter (WriterInterface):

  def __init__ (self, open_file):
    WriterInterface.__init__(self)
    self.stream = open_file

  def _write (self, text, style):
    self.stream.write(text)

class LogWriter (WriterInterface):

  def __init__ (self, open_file):
    super(LogWriter, self).__init__()
    self.stream = open_file

  @classmethod
  def formatText (cls, text, style):
    if text is None :
      return ''

    if isinstance(text, unicode) :
      text = text.encode(ENCODING, u'replace')
    else :
      text = str(text)

    if style == u'title' :
      line = '*' * 80
      text = '%s\n%s\n%s\n' % (line, text, line)
    elif style == u'warn':
      text = '*** %s ***' % text
    elif style == u'info':
      text = '# %s' % text
    else :
      pass
    return text

  def _write (self, text, style):
    self.stream.write(self.formatText(text, style))
